package com.libg.cn.sort;

/**
 * 插入排序
 */
public class InsertionSort {

    private InsertionSort() {
    }

    public static <E extends Comparable<E>> void sort2(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            //将arr[i]插入到合适的位置
            E t = arr[i];
            int j;
            for (j=i;j-1>=0&&t.compareTo(arr[j-1])<0;j--) {
                arr[j]=arr[j-1];
            }
            arr[j]=t;
        }

    }

    public static <E extends Comparable<E>> void sort(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j - 1 >= 0; j--) {
                if (arr[j].compareTo(arr[j - 1]) < 0) {
                    swap(arr, j, j - 1);
                } else {
                    break;
                }
            }
        }

    }

    private static <E> void swap(E[] arrs, int i, int j) {
        E temp = arrs[i];
        arrs[i] = arrs[j];
        arrs[j] = temp;
    }

}
